package com.brisk.common.utils.sensitiveWord;

import java.io.*;
import java.util.*;

/**
 * @author PengFei Deng
 * @title: SensitiveWordInit
 * @projectName huangyuan
 * @description: TODO
 * @date 2022/5/1013:24
 */
public class SensitiveWordInit {


    @SuppressWarnings("rawtypes")
    public static HashMap sensitiveWordMap; //存放敏感词汇的集合


    public SensitiveWordInit() {
        //文件存放的出生目录
        String path = "/home/app/sensitiveWork";
        System.out.println("初始化敏感词库开始: " + path);
        this.initKeyWord(path);
        System.out.println("初始化敏感词库结束");
    }


    /**
     * 初始化敏感词库存放到Map集合中
     */
    public void initKeyWord(String path) {
        try {
            //读取敏感词库将敏感词库加入到HashMap中
            addSensitiveWordToHashMap(readSensitiveWordFile(path));
            //spring获取application，然后application.setAttribute("sensitiveWordMap",sensitiveWordMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // return sensitiveWordMap;
    }


    /**
     * 读取敏感词库，将敏感词放入HashSet中，构建一个DFA算法模型：<br>
     * 中 = {
     * isEnd = 0
     * 国 = {<br>
     * isEnd = 1
     * 人 = {isEnd = 0
     * 民 = {isEnd = 1}
     * }
     * 男  = {
     * isEnd = 0
     * 人 = {
     * isEnd = 1
     * }
     * }
     * }
     * }
     * 五 = {
     * isEnd = 0
     * 星 = {
     * isEnd = 0
     * 红 = {
     * isEnd = 0
     * 旗 = {
     * isEnd = 1
     * }
     * }
     * }
     * }
     *
     * @param keyWordSet 敏感词库
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    private void addSensitiveWordToHashMap(Set<String> keyWordSet) {
        sensitiveWordMap = new HashMap(keyWordSet.size());     //初始化敏感词容器，减少扩容操作
        String key;
        Map nowMap;
        Map<String, String> newWorMap;
        //迭代keyWordSet
        for (String s : keyWordSet) {
            key = s;    //关键字
            nowMap = sensitiveWordMap;
            for (int i = 0; i < key.length(); i++) {
                char keyChar = key.charAt(i);       //转换成char型
                Object wordMap = nowMap.get(keyChar);       //获取

                if (wordMap != null) {        //如果存在该key，直接赋值
                    nowMap = (Map) wordMap;
                } else {     //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                    newWorMap = new HashMap<>();
                    newWorMap.put("isEnd", "0");     //不是最后一个
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if (i == key.length() - 1) {
                    nowMap.put("isEnd", "1");    //最后一个
                }
            }
        }
    }


    /**
     * 读取敏感词库中的内容，将内容添加到set集合中
     */
    @SuppressWarnings("resource")
    private Set<String> readSensitiveWordFile(String path) {
        Set<String> set = new HashSet<>();
        List<String> sensitiveWordPath = Arrays.asList("/else.txt", "/reactionary.txt", "/violence.txt", "/livelihood.txt", "/erotic.txt", "/corruption.txt");
        for (String txtPath : sensitiveWordPath) {
            File file = new File(path + File.separator + txtPath);    //读取敏感词文件
            //字符编码
            InputStreamReader read = null;
            try {
                read = new InputStreamReader(new FileInputStream(file), "GBK");
                if (file.isFile() && file.exists()) {      //文件流是否存在
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String txt;
                    while ((txt = bufferedReader.readLine()) != null) {    //读取文件，将文件内容放入到set中
                        set.add(txt);
                    }
                } else {         //不存在抛出异常信息
                    throw new Exception("敏感词库文件不存在");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (read != null) {
                        read.close();     //关闭文件流
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return set;
    }


}
